package com.landerer.service;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

import com.landerer.model.Employee;

public class EmployeeService implements EmployeeServiceBusiness {

	private EntityManager entityManager;
	
	public EmployeeService(EntityManager entityManager) {
		this.entityManager = entityManager;
	}
	
	@Override
	public Employee createEmployee(String name, long salary) {
		Employee employee = new Employee(System.currentTimeMillis());
		employee.setName(name);
		employee.setSalary(salary);
		this.entityManager.persist(employee);
		return employee;
	}

	@Override
	public Employee findEmployeeById(long id) {
		return this.entityManager.find(Employee.class, id);
	}

	@Override
	public List<Employee> findAllEmployees() {
		TypedQuery<Employee> query = this.entityManager.createQuery("Select e from Employee e", Employee.class);
		return query.getResultList();
	}

	@Override
	public void deleteAllEmployees() {
		Query query = this.entityManager.createQuery("Delete from Employee e");
		query.executeUpdate();
	}

	@Override
	public void updateEmployee(long id, String name, long salary) {
		Query query = this.entityManager.createNativeQuery("UPDATE employee set name = #name, salary = #salary where id = #id");
		query.setParameter("name", name);
		query.setParameter("salary", salary);
		query.setParameter("id", id);
		query.executeUpdate();
	}
}
